package com.ruoyi.web.controller.ism;

import java.util.ArrayList;
import java.util.List;
import javax.servlet.http.HttpServletResponse;

import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.ism.domain.IsmCustIntegralImport;
import com.ruoyi.ism.domain.IsmCustManageImport;
import com.ruoyi.ism.domain.IsmIntegralRecord;
import com.ruoyi.ism.service.IIsmIntegralRecordService;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.ism.domain.IsmCustManage;
import com.ruoyi.ism.service.IIsmCustManageService;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;
import org.springframework.web.multipart.MultipartFile;

/**
 * 客户管理Controller
 * 
 * @author ruoyi
 * @date 2024-07-19
 */
@RestController
@RequestMapping("/ism/custManage")
public class IsmCustManageController extends BaseController
{
    @Autowired
    private IIsmCustManageService ismCustManageService;

    @Autowired
    private IIsmIntegralRecordService ismIntegralRecordService;

    /**
     * 查询客户管理列表
     */
    @PreAuthorize("@ss.hasPermi('ism:custManage:list')")
    @GetMapping("/list")
    public TableDataInfo list(IsmCustManage ismCustManage)
    {
        startPage();
        List<IsmCustManage> list = ismCustManageService.selectIsmCustManageList(ismCustManage);
        return getDataTable(list);
    }

    /**
     * 导出客户管理列表
     */
    @PreAuthorize("@ss.hasPermi('ism:custManage:export')")
    @Log(title = "客户管理", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, IsmCustManage ismCustManage)
    {
        List<IsmCustManage> list = ismCustManageService.selectIsmCustManageList(ismCustManage);
        ExcelUtil<IsmCustManage> util = new ExcelUtil<IsmCustManage>(IsmCustManage.class);
        util.exportExcel(response, list, "客户管理数据");
    }

    @Log(title = "客户管理", businessType = BusinessType.IMPORT)
    @PreAuthorize("@ss.hasPermi('ism:custManage:import')")
    @PostMapping("/importData")
    public AjaxResult importData(MultipartFile file, boolean updateSupport) throws Exception
    {
        ExcelUtil<IsmCustManage> util = new ExcelUtil<IsmCustManage>(IsmCustManage.class);
        List<IsmCustManage> custManageList = util.importExcel(file.getInputStream());
        String operName = getUsername();
        String message = ismCustManageService.importCustManage(custManageList, updateSupport, operName);
        return success(message);
    }

    @PostMapping("/importTemplate")
    public void importTemplate(HttpServletResponse response)
    {
        ExcelUtil<IsmCustManageImport> util = new ExcelUtil<IsmCustManageImport>(IsmCustManageImport.class);
        util.importTemplateExcel(response, "客户数据");
    }

    /**
     * 获取客户管理详细信息
     */
    @PreAuthorize("@ss.hasPermi('ism:custManage:query')")
    @GetMapping(value = "/{custId}")
    public AjaxResult getInfo(@PathVariable("custId") Long custId)
    {
        return success(ismCustManageService.selectIsmCustManageByCustId(custId));
    }

    /**
     * 新增客户管理
     */
    @PreAuthorize("@ss.hasPermi('ism:custManage:add')")
    @Log(title = "客户管理", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody IsmCustManage ismCustManage)
    {
        IsmCustManage u = ismCustManageService.selectIsmCustManageByPhonenumber(ismCustManage.getPhonenumber());
        if (StringUtils.isNull(u))
        {
            ismCustManage.setCreateBy(getUsername());
            return toAjax(ismCustManageService.insertIsmCustManage(ismCustManage));
        }
            return error("新增失败，手机号码已存在");
    }

    /**
     * 修改客户管理
     */
    @PreAuthorize("@ss.hasPermi('ism:custManage:edit')")
    @Log(title = "客户管理", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody IsmCustManage ismCustManage)
    {
        Long custId = ismCustManage.getCustId();
        IsmCustManage u = ismCustManageService.selectIsmCustManageByCustId(custId);
        String phonenumber = ismCustManage.getPhonenumber();
        String uPhonenumber = u.getPhonenumber();
        if(!phonenumber.equals(uPhonenumber)){
            IsmCustManage cust = ismCustManageService.selectIsmCustManageByPhonenumber(phonenumber);
            if (StringUtils.isNull(u))
            {
                ismCustManage.setUpdateBy(getUsername());
                return toAjax(ismCustManageService.updateIsmCustManage(ismCustManage));
            }else{
                return error("更新失败，存在相同的手机号码号码");
            }

        }
        return toAjax(ismCustManageService.updateIsmCustManage(ismCustManage));
    }

    /**
     * 删除客户管理
     */
    @PreAuthorize("@ss.hasPermi('ism:custManage:remove')")
    @Log(title = "客户管理", businessType = BusinessType.DELETE)
	@DeleteMapping("/{custIds}")
    public AjaxResult remove(@PathVariable Long[] custIds)
    {
        return toAjax(ismCustManageService.deleteIsmCustManageByCustIds(custIds));
    }

    /**
     * 查询客户管理列表
     */
    @PreAuthorize("@ss.hasPermi('ism:custManage:list')")
    @GetMapping("/listIntegra")
    public TableDataInfo listIntegra(IsmCustManage ismCustManage)
    {
        startPage();
        List<IsmCustManage> list = ismCustManageService.selectIsmCustIntegralList(ismCustManage);
        return getDataTable(list);
    }

    /**
     * 客户积分登记
     */
    @PreAuthorize("@ss.hasPermi('ism:custManage:edit')")
    @Log(title = "客户管理", businessType = BusinessType.UPDATE)
    @PutMapping("/updateIntegra")
    public AjaxResult updateIsmCustManageIntegral(@RequestBody IsmCustManage ismCustManage)
    {
        String familySn = ismCustManage.getFamilySn();
        String holderName = ismCustManage.getHouseholderName();
        String remark = ismCustManage.getRemark();
        long familyIntegralNew = ismCustManage.getFamilyIntegral();
        List<IsmCustManage> list = ismCustManageService.selectIsmCustIntegralByfamilyInfo(ismCustManage);
        if(list.size()>1){
            return error("积分登记失败，请联系系统管理员");
        }
        IsmCustManage tmp = list.get(0);
        long familyIntegralBefore = tmp.getFamilyIntegral();
        long familyIntegralAfter = familyIntegralBefore + familyIntegralNew;
        if(familyIntegralAfter<0){
            return error("积分登记失败，积分调整后已为负数");
        }
        IsmIntegralRecord ismIntegralRecord = new IsmIntegralRecord();
        ismIntegralRecord.setFamilySn(familySn);
        ismIntegralRecord.setHouseholderName(holderName);
        ismIntegralRecord.setIntegralBefore(familyIntegralBefore);
        ismIntegralRecord.setIntegralExchange(familyIntegralNew);
        ismIntegralRecord.setIntegralAfter(familyIntegralAfter);
        ismIntegralRecord.setCreateBy(getUsername());
        ismIntegralRecord.setRemark(remark);
        ismIntegralRecordService.insertIsmIntegralRecord(ismIntegralRecord);

        ismCustManage.setFamilyIntegral(familyIntegralAfter);
        return toAjax(ismCustManageService.updateIsmCustManageIntegral(ismCustManage));
    }

    @Log(title = "客户管理", businessType = BusinessType.IMPORT)
    @PreAuthorize("@ss.hasPermi('ism:custManage:import')")
    @PostMapping("/importIntegralData")
    public AjaxResult importIntegralData(MultipartFile file, boolean updateSupport) throws Exception
    {
        ExcelUtil<IsmCustIntegralImport> util = new ExcelUtil<IsmCustIntegralImport>(IsmCustIntegralImport.class);
        List<IsmCustIntegralImport> custManageImportList = util.importExcel(file.getInputStream());
        List<IsmCustManage> custManageList= new ArrayList<IsmCustManage>();
        for(int i=0;i<custManageImportList.size();i++){
            IsmCustIntegralImport ismCustIntegralImport =custManageImportList.get(i);
            IsmCustManage ismCustManage = new IsmCustManage();
            String familySn = ismCustIntegralImport.getFamilySn();
            String householderName = ismCustIntegralImport.getHouseholderName();
            long familyIntegral = ismCustIntegralImport.getFamilyIntegral();
            String remark = ismCustIntegralImport.getRemark();
            ismCustManage.setFamilySn(familySn);
            ismCustManage.setHouseholderName(householderName);
            ismCustManage.setFamilyIntegral(familyIntegral);
            ismCustManage.setRemark(remark);
            custManageList.add(ismCustManage);
        }
        String operName = getUsername();
        String message = ismCustManageService.importCustIntegral(custManageList, updateSupport, operName);
        return success(message);
    }

    @PostMapping("/importIntegralTemplate")
    public void importIntegralTemplate(HttpServletResponse response)
    {
        ExcelUtil<IsmCustIntegralImport> util = new ExcelUtil<IsmCustIntegralImport>(IsmCustIntegralImport.class);
        util.importTemplateExcel(response, "客户数据");
    }

}
